var noOfPages = 256,
pagePath = "pages/small/page{0}.jpg",
largePagePath = "pages/small/page{0}.jpg",
thumbPath = "pages/thumb/rfa-{0}.jpg",
imageMapPath = "pages/{0}-regions.js",
videoPath = "pages/videos/{0}",
displayType = 'double'; // "double"; //'single';

function InitializeMe() {

    $('#all').fadeIn(1000);

    //Attach events
    $('.fullscreen').click(function () {
        var isFullScreen = fullScreenApi.isFullScreen();
        fullScreenApi[isFullScreen ? "cancelFullScreen" : "requestFullScreen"](document.documentElement);
        $(this).attr("title", isFullScreen ? "Normal View" : "Fullscreen View");
    });

    $('.fullscreen').mouseenter(function () {
        $(this).attr("title", fullScreenApi.isFullScreen() ? "Normal View" : "Fullscreen View");
    });

    $(".home").click(function () {
        location.replace("index.htm");
    });

    $(".index").click(function () {
        if ($('#list').css('display') == 'none') {
            $('#list').fadeIn(1000);
            $(".index").attr("title", "Hide Thumbnails");
        }
        else {
            $('#list').fadeOut(1000);
            $(".index").attr("title", "Show Thumbnails");
        }
    });

    $(".zoom").click(function () {
        var viewPort = $('.magazine-viewport');
        if (viewPort.zoom('value') != 1) {
            viewPort.zoom('zoomOut');
        }
        else {
            var w = viewPort.width();
            var h = viewPort.height();
            viewPort.zoom('zoomIn', { x: w / 2, y: h / 2 })
        }
    });
    
    $(".print").click(function () {
        var page = $('.magazine').turn('page');

        $('#printframe').attr('src', 'print.htm?path=' + largePagePath + "&page=" + page + "&total=" + noOfPages);

    });
    
    $(".lnk").click(function () {
           $('.magazine').turn('page', $(this).attr("data-page"));
    });

    $(".goto").click(function () {
        window.open("http://www.trucut-tool.com/", "_blank");
    });

       
//    $(".info").click(function (e) {
//        $('.infopanel')[$('.infopanel').css('display') == 'none' ? "fadeIn" : "fadeOut"](1000);
//        $('.infopanel').css({ top: e.pageY, left: e.pageX - 150 });

//        setTimeout("$('.infopanel').fadeOut(1000);", 10000);
//    });

	$('.magazine').turn({

	        display: displayType,

			// Magazine width

			width: 900, //1020, //1120, //922,

			// Magazine height

			height: 604, //664, //600,

			// Elevation will move the peeling corner this number of pixels by default

			elevation: 2,
			
			// Hardware acceleration

			acceleration: !isChrome(),

			// Enables gradients

			gradients: true,
			
			// Auto center this flipbook

			autoCenter: true,

			// The number of pages

			pages: noOfPages,


			duration: $.browser.msie ? 1000 : 500,

			// Events
			when: {

			turning: function(event, page, view) {
            			    

				var book = $(this),
				currentPage = book.turn('page'),
				pages = book.turn('pages');
		
				// Update the current URI

				Hash.go(pagePath.replace("{0}", page)).update();


				// Show and hide navigation buttons

				disableControls(page);
				

//				$('.thumbnails .page-'+currentPage).
//					parent().
//					removeClass('current');

//				$('.thumbnails .page-'+page).
//					parent().
//					addClass('current');

			},

			turned: function(event, page, view) {

				disableControls(page);

				$(this).turn('center');

				if (page==1) { 
					$(this).turn('peel', 'br');
				}

			},

			missing: function (event, pages) {

				// Add pages that aren't in the magazine

				for (var i = 0; i < pages.length; i++)
					addPage(pages[i], $(this));

			}
		}

	});

	// Zoom.js

    $('<div />', { 'class': 'esc' }).
					html('<div>Press F11 to full screen view</div>').
						appendTo($('body')).
						delay(2500).
						animate({ opacity: 0 }, 500, function () {
							$(this).remove();
						});

						$('.magazine-viewport').zoom({
						    flipbook: $('.magazine'),
						    max: function () {

						        return largeMagazineWidth() / $('.magazine').width();

						    },
						    when: {
						        tap: function (event) {

						            var region = $(event.target);


						            //if (region.hasClass('region') || region.hasClass('rgn'))
						            if (getReagionType(region))
						                return;

						            if ($(this).zoom('value') == 1) {
						                $('.magazine').
						removeClass('animated').
						addClass('zoom-in');
						                $(this).zoom('zoomIn', event);
						            } else {
						                $(this).zoom('zoomOut');
						            }
						        },

						        resize: function (event, scale, page, pageElement) {

						            pageElement.css('cursor', scale == 1 ? 'url(../runtime/styles/images/zoomIn.cur), url(../runtime/styles/images/zoomIn.png), default' : 'url(../runtime/styles/images/zoomOut.cur), url(../runtime/styles/images/zoomOut.png), default');

						            $('.page-corner').css('cursor', 'pointer');

						            if (scale == 1)
						                loadSmallPage(page, pageElement);
						            else
						                loadLargePage(page, pageElement);

						        },

						        zoomIn: function () {

						            var rgns = $('.rgn');
						            for (var r = 0; r < rgns.length; r++) {
						                var rgn = $(rgns[r]);
						                rgn.css({ width: rgn.width() * 1.75, height: rgn.height() * 1.75 });
						            }

						            //$('.loader').css({ left: ((1120 - 32) / 2) * 2, top: ((664 - 32) / 2) * 2 });
						            $('.next-button').hide();
						            $('.previous-button').hide();
						            $(".poweredby").hide();

						            var sp = false; // ($('.magazine').turn('page') == $('.magazine').turn('pages') || $('.magazine').turn('page') == 1) ? true : false;

						            $("#logo")[sp ? "show" : "hide"]();
						            $(".actionbarleft")[sp ? "show" : "hide"]();
						            $('.magazine').addClass('zoom-in');

						            if (!window.escTip && !$.isTouch) {
						                escTip = true;

						            $('<div />', { 'class': 'esc' }).
						            html('<div>Press ESC to exit</div>').
							            appendTo($('body')).
							            delay(2000).
							            animate({ opacity: 0 }, 500, function () {
							                $(this).remove();
							            });
						            }
						        },

						        zoomOut: function () {

						            //$('.loader').css({ left: ((1120 - 32) / 2), top: ((664 - 32) / 2) });

						            $('.esc').hide();

						            setTimeout(function () {
						                $('.magazine').addClass('animated').removeClass('zoom-in');
						                resizeViewport();
						                disableControls($('.magazine').turn('page'));
						            }, 0);

						            var rgns = $('.rgn');
						            for (var r = 0; r < rgns.length; r++) {
						                var rgn = $(rgns[r]);
						                rgn.css({ width: rgn.width() / 1.75, height: rgn.height() / 1.75 });
						            }
						        },

						        swipeLeft: function () {

						            $('.magazine').turn('next');

						        },

						        swipeRight: function () {

						            $('.magazine').turn('previous');

						        }
						    }
						});


//	//load defaults
//	$('.magazine').turn('next');

	// Using arrow keys to turn the page

	$(document).keydown(function (e) {

	    var previous = 37, next = 39, esc = 27;

	    switch (e.keyCode) {
	        case previous:
	            var currentPage = String($('.magazine').turn('page'));

	            //if (currentPage != "2" && currentPage != "3") {

	                // left arrow
	                $('.magazine').turn('previous');
	            //}
	          
	            e.preventDefault();

	            break;
	        case next:

	            //right arrow
	            $('.magazine').turn('next');
	            e.preventDefault();

	            break;
	        case esc:

	            $('.magazine-viewport').zoom('zoomOut');
	            e.preventDefault();

	            break;
	    }
	});

	// URIs - Format #/page/1 

	Hash.on('^page\/([0-9]*)$', {
		yep: function(path, parts) {
			var page = parts[1];

			if (page!==undefined) {
				if ($('.magazine').turn('is'))
					$('.magazine').turn('page', page);
			}

		},
		nop: function(path) {

			if ($('.magazine').turn('is'))
				$('.magazine').turn('page', 1);
		}
	});


	$(window).resize(function() {
		resizeViewport();
	}).bind('orientationchange', function() {
		resizeViewport();
	});
/*
	// Events for thumbnails
	$('.thumbnails').click(function(event) {
		
		var page;

		if (event.target && (page=/page-([0-9]+)/.exec($(event.target).attr('class'))) ) {
		
			$('.magazine').turn('page', page[1]);
		}
	});

	$('.thumbnails li').
		bind($.mouseEvents.over, function() {
			
			$(this).addClass('thumb-hover');

		}).bind($.mouseEvents.out, function() {
			
			$(this).removeClass('thumb-hover');

		});

	if ($.isTouch) {
	
		$('.thumbnails').
			addClass('thumbanils-touch').
			bind($.mouseEvents.move, function(event) {
				event.preventDefault();
			});

	} else {

		$('.thumbnails ul').mouseover(function() {

			$('.thumbnails').addClass('thumbnails-hover');

		}).mousedown(function() {

			return false;

		}).mouseout(function() {

			$('.thumbnails').removeClass('thumbnails-hover');

		});
	}
	*/

	// Regions

	if ($.isTouch) {
		$('.magazine').bind('touchstart', regionClick);
	} else {
		$('.magazine').click(regionClick);
	}

	// Events for the next button

	$('.next-button').bind($.mouseEvents.over, function() {
		
		$(this).addClass('next-button-hover');

	}).bind($.mouseEvents.out, function() {
		
		$(this).removeClass('next-button-hover');

	}).bind($.mouseEvents.down, function() {
		
		$(this).addClass('next-button-down');

	}).bind($.mouseEvents.up, function() {
		
		$(this).removeClass('next-button-down');

	}).click(function() {
		
		$('.magazine').turn('next');

	});

	// Events for the next button
	
	$('.previous-button').bind($.mouseEvents.over, function() {
		
		$(this).addClass('previous-button-hover');

	}).bind($.mouseEvents.out, function() {
		
		$(this).removeClass('previous-button-hover');

	}).bind($.mouseEvents.down, function() {
		
		$(this).addClass('previous-button-down');

	}).bind($.mouseEvents.up, function() {
		
		$(this).removeClass('previous-button-down');

	}).click(function() {
		
		$('.magazine').turn('previous');

	});


	resizeViewport();

	$('.magazine').addClass('animated');

}

// **************************** Add or load pages ****************************************//
function addPage(page, book) {

	var id, pages = book.turn('pages');

	// Create a new element for this page
	var element = $('<div />', {});

	// Add the page to the flipbook
	if (book.turn('addPage', element, page)) {

		// Add the initial HTML
		// It will contain a loader indicator and a gradient
		element.html('<div class="gradient"></div><div class="loader"></div>');

		// Load the page
		loadPage(page, element);
	}

}

function loadPage(page, pageElement) {

	// Create an image element

	var img = $('<img />');

	img.mousedown(function(e) {
		e.preventDefault();
	});

	img.load(function() {
		
		// Set the size
		$(this).css({width: '100%', height: '100%'});

		// Add the image to the page after loaded

		$(this).appendTo(pageElement);

		// Remove the loader indicator
		
		pageElement.find('.loader').remove();
	});

	// Load the page

    img.attr('src', pagePath.replace("{0}", page));

	loadRegions(page, pageElement);

}

// Load large page
function loadLargePage(page, pageElement) {
    
    var lft = (($(window).width() - 114) / 2);
    var tp = (($(window).height() - 64) / 2);

    var ldr = $('.zoomloader');
    if (!ldr || ldr.length == 0) {
        ldr = $('<div class="zoomloader" style="left:' + (lft) + 'px; top:' + (tp) + 'px;"></div>');
        ldr.appendTo($('body'));
    }
    ldr.show();

    pageElement.find('img').css('cursor', 'url(../runtime/styles/images/zoomOut.cur), url(../runtime/styles/images/zoomOut.png), default');

	var img = $('<img />');

	img.load(function() {

		var prevImg = pageElement.find('img');
		$(this).css({width: '100%', height: '100%'});
		$(this).appendTo(pageElement);
		prevImg.remove();
		ldr.hide();
		
	});

	// Loadnew page

    img.attr('src', largePagePath.replace("{0}", page));
    img.mousedown(md1);
    img.mouseup(mu1);
}

function md1() {
    $(this).css('cursor', 'move');
}

function mu1() {
    $(this).css('cursor', 'url(../runtime/styles/images/zoomOut.cur), url(../runtime/styles/images/zoomOut.png), default');
}

// Load small page
function loadSmallPage(page, pageElement) {

//    if (String(page) == "1") {
//        $('.magazine').turn('page', 2);
//        return;
//    }

	var img = pageElement.find('img');

	img.css({width: '100%', height: '100%'});

	img.unbind('load');
	// Loadnew page

	img.attr('src', pagePath.replace("{0}", page));
    
	img.unbind('mousedown', md1);
	img.unbind('mouseup', mu1);

	img.css('cursor', 'url(../runtime/styles/images/zoomIn.cur), url(../runtime/styles/images/zoomIn.png), default');
}

// **************************** regions ****************************************//
function loadRegions(page, element) {
    return;
    if (page == 3) {
        var pageRegion = {
            x: 77,
            y: 120,
            height: 190,
            width: 325,
            data: { url: 'YKK_AP' }
        };
        pageRegion["class"] = "video";
        addRegion(pageRegion, element);
    }
    else if (page == 2) {

        var pageRegion = {
            x: 120,
            y: 29,
            height: 100,
            width: 341,
            data: { page: 6 }
        };
        pageRegion["class"] = "to-page";
        addRegion(pageRegion, element);

        pageRegion = {
            x: 120,
            y: 136,
            height: 100,
            width: 341,
            data: { page: 5 }
        };
        pageRegion["class"] = "to-page";
        addRegion(pageRegion, element);

        pageRegion = {
            x: 120,
            y: 246,
            height: 100,
            width: 341,
            data: { }
        };
        pageRegion["class"] = "to-page";
        addRegion(pageRegion, element);

        pageRegion = {
            x: 120,
            y: 356,
            height: 100,
            width: 341,
            data: {}
        };
        pageRegion["class"] = "to-page";
        addRegion(pageRegion, element);

        pageRegion = {
            x: 120,
            y: 470,
            height: 100,
            width: 341,
            data: {}
        };
        pageRegion["class"] = "to-page";
        addRegion(pageRegion, element);
    }


//	return; //To do: load json and create inplace links and images later

//	$.getJSON(imageMapPath.replace("{0}", page)).
//		done(function(data) {

//			$.each(data, function(key, region) {
//				addRegion(region, element);
//			});
//		});
}

function addRegion(region, pageElement) {

    var reg = null;
    switch (region['class']) {
        case "video":
            //poster = "my_video_poster.png";
            reg = $('<div class="rgn region-container"><video class="rgn video-js vjs-default-skin" controls preload="auto" width="' + region.width + '" height="' + region.height + '" data-setup="{}"><source src="' + videoPath.replace("{0}", region.data.url) + '.mp4" type="video/mp4"><source src="' + videoPath.replace("{0}", region.data.url) + '.webm" type="video/webm"></video></div>');
            //reg = $('<div class="rgn region-container"> <video class="rgn" width="' + region.width + '" height="' + region.height + '" controls="controls"><source src="' + videoPath.replace("{0}", region.data.url) + '" type="video/mp4"></video> </div>');
            break;
        default:
            reg = $('<div />', { 'class': 'rgn region-container ' + region['class'] });
            break;
    }

	//var reg = $('<div />', {'class': 'region  ' + region['class']}),
		var options = $('.magazine').turn('options'),
		pageWidth = options.width/2,
		pageHeight = options.height;

	reg.css({
		top: Math.round(region.y/pageHeight*100)+'%',
		left: Math.round(region.x/pageWidth*100)+'%',
		width: Math.round(region.width/pageWidth*100)+'%',
		height: Math.round(region.height/pageHeight*100)+'%'
	}).attr('region-data', $.param(region.data||''));


	reg.appendTo(pageElement);
}

function regionClick(event) {

    var region = $(event.target);

   var regionType  = getReagionType(region);

    if (regionType) {
        //event.preventDefault();
        return processRegion(region, $.trim(regionType), event);
    }

//	var region = $(event.target);
//	if (region.hasClass('region')) {
//		
//		var regionType = $.trim(region.attr('class').replace('region', ''));

//		return processRegion(region, regionType);
//	}

}

function getReagionType(region) {

    var targetClass = region.prop("class");

    var tmpTarget = region;
    while (!targetClass) {
        tmpTarget = region.parent('div');
        targetClass = tmpTarget.prop("class");
    }

    if (region.hasClass('region') || region.hasClass('rgn') || targetClass.indexOf('vjs') != -1) {
        return targetClass.indexOf('vjs') != -1 ? 'video' : targetClass.replace('rgn', '').replace('region-container', '').replace('region', '');
    }
}

function processRegion(region, regionType) {

	data = decodeParams(region.attr('region-data'));

	switch (regionType) {
	    case "video":
	        break;
        case 'link' :

			window.open(data.url);

		break;
		case 'zoom' :

			var regionOffset = region.offset(),
				viewportOffset = $('.magazine-viewport').offset(),
				pos = {
					x: regionOffset.left-viewportOffset.left,
					y: regionOffset.top-viewportOffset.top
				};

			$('.magazine-viewport').zoom('zoomIn', pos);

		break;
		case 'to-page' :
            if(data.page)
			    $('.magazine').turn('page', data.page);

		break;
	}

}

// http://code.google.com/p/chromium/issues/detail?id=128488
function isChrome() {
	return navigator.userAgent.indexOf('Chrome')!=-1;
}

function disableControls(page) {
    var showPoweredBy = true; // (page == 1 || page == $('.magazine').turn('pages')) ? true : false;
    try {


        if ($('.magazine').hasClass('zoom-in')) //skip for zoom
            return;
    }
    catch (e) { }

    if (page == 1) //1) 
    {
        $('.previous-button').hide();
        $(".previouspg").hide();
    }
    else 
    {
        $('.previous-button').show();
        $(".previouspg").show();
    }

    if (page == $('.magazine').turn('pages')) {
        $('.next-button').hide();
        $(".nextpg").hide();
    }
    else 
    {
        $('.next-button').show();
        $(".nextpg").show();
    }

    $(".poweredby")[showPoweredBy ? "show" : "hide"]();
    $("#logo")[showPoweredBy ? "show" : "hide"]();
    $(".actionbarleft")[showPoweredBy ? "show" : "hide"]();
}

// Set the width and height for the viewport
function resizeViewport() {

	var width = $(window).width(),
		height = $(window).height(),
		options = $('.magazine').turn('options');

	$('.magazine').removeClass('animated');

	$('.magazine-viewport').css({
		width: width,
		height: height
	}).
	zoom('resize');

	if ($('.magazine').turn('zoom')==1) {
		var bound = calculateBound({
			width: options.width,
			height: options.height,
			boundWidth: Math.min(options.width, width),
			boundHeight: Math.min(options.height, height)
		});

		if (bound.width%2!==0)
			bound.width-=1;

			
		if (bound.width!=$('.magazine').width() || bound.height!=$('.magazine').height()) {

			$('.magazine').turn('size', bound.width, bound.height);

			if ($('.magazine').turn('page')==1)
				$('.magazine').turn('peel', 'br');

			$('.next-button').css({height: bound.height, backgroundPosition: '-38px '+(bound.height/2-32/2)+'px'});
			$('.previous-button').css({height: bound.height, backgroundPosition: '-4px '+(bound.height/2-32/2)+'px'});
		}

		$('.magazine').css({top: -bound.height/2, left: -bound.width/2});
	}

	var magazineOffset = $('.magazine').offset(),
		boundH = height - magazineOffset.top - $('.magazine').height(),
		marginTop = (boundH - $('.thumbnails > div').height()) / 2;

	if (marginTop<0) 
	{
		$('.thumbnails').css({height:1});
	} else {
		$('.thumbnails').css({height: boundH});
		$('.thumbnails > div').css({marginTop: marginTop});
	}

	if (magazineOffset.top<$('.made').height())
		$('.made').hide();
	else
		$('.made').show();

	$('.magazine').addClass('animated');
	
}

// Width of the flipbook when zoomed in

function largeMagazineWidth() {

    return 1020 * 1.75; // 1960; // 1120 * 1.75

}

// decode URL Parameters

function decodeParams(data) {
    data = data ? data : '';
	var parts = data.split('&'), d, obj = {};

	for (var i =0; i<parts.length; i++) {
		d = parts[i].split('=');
		obj[decodeURIComponent(d[0])] = decodeURIComponent(d[1]);
	}

	return obj;
}

// Calculate the width and height of a square within another square

function calculateBound(d) {
	
	var bound = {width: d.width, height: d.height};

	if (bound.width>d.boundWidth || bound.height>d.boundHeight) {
		
		var rel = bound.width/bound.height;

		if (d.boundWidth/rel>d.boundHeight && d.boundHeight*rel<=d.boundWidth) {
			
			bound.width = Math.round(d.boundHeight*rel);
			bound.height = d.boundHeight;

		} else {
			
			bound.width = d.boundWidth;
			bound.height = Math.round(d.boundWidth/rel);
		
		}
	}
		
	return bound;
}


//fullscreen support

(function () {
    var 
        fullScreenApi = {
            supportsFullScreen: false,
            nonNativeSupportsFullScreen: false,
            isFullScreen: function () { return false; },
            requestFullScreen: function () { },
            cancelFullScreen: function () { },
            fullScreenEventName: '',
            prefix: ''
        },
        browserPrefixes = 'webkit moz o ms khtml'.split(' ');

    // check for native support
    if (typeof document.cancelFullScreen != 'undefined') {
        fullScreenApi.supportsFullScreen = true;
    } else {
        // check for fullscreen support by vendor prefix
        for (var i = 0, il = browserPrefixes.length; i < il; i++) {
            fullScreenApi.prefix = browserPrefixes[i];

            if (typeof document[fullScreenApi.prefix + 'CancelFullScreen'] != 'undefined') {
                fullScreenApi.supportsFullScreen = true;

                break;
            }
        }
    }

    // update methods to do something useful
    if (fullScreenApi.supportsFullScreen) {
        fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';

        fullScreenApi.isFullScreen = function () {
            switch (this.prefix) {
                case '':
                    return document.fullScreen;
                case 'webkit':
                    return document.webkitIsFullScreen;
                default:
                    return document[this.prefix + 'FullScreen'];
            }
        }
        fullScreenApi.requestFullScreen = function (el) {
            return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
        }
        fullScreenApi.cancelFullScreen = function (el) {
            return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
        }
    }
    else if (typeof window.ActiveXObject !== "undefined") { // IE.
        fullScreenApi.nonNativeSupportsFullScreen = true;
        fullScreenApi.requestFullScreen = fullScreenApi.requestFullScreen = function (el) {
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
        fullScreenApi.isFullScreen = function () {
            return document.body.clientHeight == screen.height && document.body.clientWidth == screen.width;
        }
    }

    // jQuery plugin
    if (typeof jQuery != 'undefined') {
        jQuery.fn.requestFullScreen = function () {

            return this.each(function () {
                if (fullScreenApi.supportsFullScreen) {
                    fullScreenApi.requestFullScreen(this);
                }
            });
        };
    }

    // export api
    window.fullScreenApi = fullScreenApi;
})();